# 用户偏好管理的视图文件
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime

from myadmin.models import UserPreferences, FoodCategories, Foods, Users

# 用户偏好管理
def index(request, pIndex=1):
    """用户偏好列表页"""
    # 关键：预加载关联表数据，优化查询性能
    ulist = UserPreferences.objects.select_related(
        'user', 'preferred_category', 'preferred_food'
    ).all()
    mywhere = []
    
    # 排序处理
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', 'asc')
    if sort:
        if order == 'desc':
            sort = f'-{sort}'
        try:
            ulist = ulist.order_by(sort)
            mywhere.extend([f'sort={sort.replace("-", "")}', f'order={order}'])
        except:
            pass
    
    # 搜索处理
    kw = request.GET.get("keyword", None)
    if kw:
        ulist = ulist.filter(
            Q(user__username__contains=kw) | 
            Q(preferred_food__food_name__contains=kw) |
            Q(preferred_category__category_name__contains=kw) |
            Q(preference_level__contains=kw)
        )
        mywhere.append(f'keyword={kw}')
    
    # 用户筛选
    uid = request.GET.get('user', '')
    if uid:
        ulist = ulist.filter(user_id=uid)
        mywhere.append(f'user={uid}')
    
    # 食物类别筛选
    cid = request.GET.get('category', '')
    if cid:
        ulist = ulist.filter(preferred_category_id=cid)
        mywhere.append(f'category={cid}')
    
    # 食物筛选
    fid = request.GET.get('food', '')
    if fid:
        ulist = ulist.filter(preferred_food_id=fid)
        mywhere.append(f'food={fid}')
    
    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(ulist, 5)  # 每页5条记录
    maxpages = page.num_pages
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)
    plist = page.page_range
    
    # 获取关联数据（用于筛选框）
    users = Users.objects.all()
    categories = FoodCategories.objects.all()
    foods = Foods.objects.all()
    
    context = {
        "preferencelist": list2,
        'users': users,
        'categories': categories,
        'foods': foods,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere,
        'selected_uid': uid,
        'selected_cid': cid,
        'selected_fid': fid
    }
    return render(request, "myadmin/userpreferences/index.html", context)

def add(request):
    """加载用户偏好添加表单"""
    users = Users.objects.all()
    categories = FoodCategories.objects.all()
    foods = Foods.objects.all()
    context = {
        'users': users,
        'categories': categories,
        'foods': foods
    }
    return render(request, "myadmin/userpreferences/add.html", context)

def insert(request):
    """执行用户偏好添加"""
    try:
        ob = UserPreferences()
        # 必选字段验证
        user_id = request.POST.get('user_id')
        if not user_id:
            raise ValueError("用户为必填项！")
        ob.user_id = user_id
        
        # 类别和食物至少选一个
        category_id = request.POST.get('preferred_category_id')
        food_id = request.POST.get('preferred_food_id')
        if not category_id and not food_id:
            raise ValueError("食物类别和具体食物至少需选择一项！")
        
        ob.preferred_category_id = category_id if category_id else None
        ob.preferred_food_id = food_id if food_id else None
        
        # 偏好程度
        ob.preference_level = request.POST.get('preference_level', '一般')
        
        ob.save()
        context = {'info': "添加成功！"}
    except Exception as err:
        print(err)
        context = {'info': f"添加失败：{str(err)}"}
    return render(request, "myadmin/info.html", context)

def edit(request, pid=0):
    """加载用户偏好编辑表单"""
    try:
        ob = UserPreferences.objects.get(preference_id=pid)
        users = Users.objects.all()
        categories = FoodCategories.objects.all()
        foods = Foods.objects.all()
        context = {
            'preference': ob,
            'users': users,
            'categories': categories,
            'foods': foods
        }
        return render(request, "myadmin/userpreferences/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': "没有找到要修改的信息！"}
    return render(request, "myadmin/info.html", context)

def update(request, pid):
    """执行用户偏好编辑"""
    try:
        ob = UserPreferences.objects.get(preference_id=pid)
        
        # 验证用户
        user_id = request.POST.get('user_id')
        if not user_id:
            raise ValueError("用户为必填项！")
        ob.user_id = user_id
        
        # 验证类别和食物至少选一个
        category_id = request.POST.get('preferred_category_id')
        food_id = request.POST.get('preferred_food_id')
        if not category_id and not food_id:
            raise ValueError("食物类别和具体食物至少需选择一项！")
        
        ob.preferred_category_id = category_id if category_id else None
        ob.preferred_food_id = food_id if food_id else None
        
        # 偏好程度
        ob.preference_level = request.POST.get('preference_level', '一般')
        
        ob.save()
        context = {'info': "修改成功！"}
    
    except UserPreferences.DoesNotExist:
        context = {'info': "修改失败：偏好记录不存在！"}
    except ValueError as e:
        context = {'info': f"修改失败：{str(e)}"}
    except Exception as e:
        print(f"修改错误详情：{str(e)}")
        context = {'info': f"修改失败：{str(e)}"}
    
    return render(request, "myadmin/info.html", context)

def delete(request, pid=0):
    """执行用户偏好删除"""
    try:
        ob = UserPreferences.objects.get(preference_id=pid)
        ob.delete()
        context = {'info': "删除成功！"}
    except UserPreferences.DoesNotExist:
        context = {'info': "删除失败：偏好记录不存在！"}
    except Exception as err:
        print(f"删除偏好时出错: {err}")
        context = {'info': "删除失败：发生未知错误！"}
    return render(request, "myadmin/info.html", context)